import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { GameComponent } from "@sapi-game/main";
import { RandomUtils } from "@sapi-game/utils";
import { PillarOfFortuneMainState } from "../states/mainState";
import { PillarOfFortuneEventActuator } from "./eventActuator";

interface EventData {
    name: string;
    onEvent: (actuator: PillarOfFortuneEventActuator) => void;
}

interface EventDataMap {
    [key: string]: EventData;
}

interface TimeEventData {
    eventList: EventData[];
    time: number;
}

const events: EventDataMap = {
    arrowRain: {
        name: "箭雨",
        onEvent: (actuator) => {
            actuator.arrowRain();
        },
    },
    ghast: {
        name: "§4恶魂来袭",
        onEvent: (actuator) => {
            actuator.Ghast();
        },
    },
    randomSwap: {
        name: "随机交换",
        onEvent: (actuator) => {
            actuator.swapPlayer();
        },
    },
    lightning_bolt: {
        name: "闪电",
        onEvent(actuator) {
            actuator.LightningBlot();
        },
    },
    borderShrink: {
        name: "§v边界收缩",
        onEvent(actuator) {
            actuator.borderShrink();
        },
    },
} as const;

export class PillarOfFortuneEvent extends GameComponent<PillarOfFortuneMainState> {
    private nextEvent?: {
        event: EventData;
        time: number;
    };

    private readonly EventTimes: TimeEventData[] = [
        {
            eventList: [events.arrowRain],
            time: 1120,
        },
        {
            eventList: [events.ghast],
            time: 1050,
        },
        {
            eventList: [events.randomSwap, events.lightning_bolt],
            time: 960,
        },
        {
            eventList: [events.borderShrink],
            time: 900,
        },
    ];

    override onAttach(): void {
        const timer = this.state.getComponent(Timer);
        this.setNextEvent(timer.time);
        const actuator = this.state.getComponent(PillarOfFortuneEventActuator);
        //订阅
        this.subscribe(timer.events.tick, (t) => {
            if (!this.nextEvent) return;
            if (t.remainingTime == this.nextEvent.time) {
                const next = this.nextEvent;
                this.context.players.title(next.event.name); //显示名称
                this.runner.runDelay(() => {
                    next.event.onEvent(actuator); //触发事件
                    this.setNextEvent(t.remainingTime); //设置下一事件
                }, 20);
            }
        });
    }

    getNextEvent() {
        return this.nextEvent;
    }

    private setNextEvent(curTime: number) {
        const next = this.EventTimes.find((e) => e.time < curTime);
        if (!next) {
            this.nextEvent = undefined;
            return;
        }
        const event = RandomUtils.choice(next.eventList);
        if (event) {
            this.nextEvent = { event: event, time: next.time };
        } else {
            this.nextEvent = undefined;
        }
    }
}
